package com.javasea.nio.chat.server;

import com.javasea.nio.chat.common.core.codc.RequestDecoder;
import com.javasea.nio.chat.common.core.codc.ResponseEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.nio.channels.Channels;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * netty服务端入门
 * @author -琴兽-
 *
 */
@Component
public class Server {

	/**
	 * 启动
	 */
	public void start() {

		//服务类
		ServerBootstrap bootstrap = new ServerBootstrap();

		//boss线程监听端口，worker线程负责数据读写
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();

		try {
			ServerBootstrap b = new ServerBootstrap();
			// 设置循环线程组事例
			b.group(bossGroup, workerGroup)
					// 设置channel工厂
					.channel(NioServerSocketChannel.class)
					.childOption(ChannelOption.SO_KEEPALIVE, true)
					// 链接缓冲池队列大小
					.option(ChannelOption.SO_BACKLOG, 1024)
					// 设置管道
					.childHandler(new ChannelInitializer<SocketChannel>() {
						@Override
						public void initChannel(SocketChannel ch) throws Exception {
							ch.pipeline().addLast(new RequestDecoder());
							ch.pipeline().addLast(new ResponseEncoder());
							ch.pipeline().addLast(new ServerHandler());
						}
					});

			//绑定端口，同步等待成功
			ChannelFuture f = b.bind(10102).sync();

			//等待服务器监听端口关闭
			f.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			//释放线程池资源
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}

	}

}
